<script setup lang='ts' name="rights-management-add">
import type { FormInstance } from 'element-plus'

import { addMenu, exploitGetGroup, getMenuNo } from '@fl/api/exploit-setting'
import UpdatedOss from '@fl/components/upLoad-oss.vue'
import { ElButton, ElCol, ElDialog, ElForm, ElFormItem, ElInput, ElMessage, ElOption, ElRow, ElSelect } from 'element-plus'
import { nextTick, reactive, ref, toRefs } from 'vue'

const props = withDefaults(defineProps<{
    appItem: any
    data?: any
    modelValue: boolean
}>(), {
    data: () => {},
})

const emits = defineEmits(['update:modelValue', 'confirm'])
const { appItem, data, modelValue } = toRefs(props)

const title = ref('新增')
const formRef = ref()

const state = { appCode: '', groupIds: [], menuCode: '', menuName: '', menuPath: '', menuUrl: '', status: '' }
const form = ref<any>({ ...state })

const groupIds = ref<any>([])
const status = [
    {
        color: 'red',
        label: '开发中',
        value: 1,
    },
    {
        color: 'blue',
        label: '已完成',
        value: 2,
    },
]

const rules = reactive<any>({
    menuCode: [
        { message: '请输入', required: true, trigger: 'blur' },
    ],
    menuName: [
        { message: '请输入', required: true, trigger: 'blur' },
    ],
    menuPath: [
        { message: '请输入', required: true, trigger: 'blur' },
    ],
    menuUrl: [
        { message: '请输入', required: true, trigger: 'blur' },
    ],
    status: [
        { message: '请选择', required: true, trigger: 'change' },
    ],
})

async function doSave(formEl: FormInstance | undefined) {
    if (!formEl)
        return
    await formEl.validate((valid, fields) => {
        if (valid) {
            addMenu({
                ...form.value,
                appCode: appItem.value.appCode,
            }).then((res: any) => {
                if (res.code === 200) {
                    close(formEl)
                    ElMessage.success('保存成功')
                    emits('confirm')
                }
                else { ElMessage({ message: res.msg, type: 'error' }) }
            }).catch((err) => {
                const message = err?.response?.data?.message || err
                ElMessage({ message, type: 'error' })
            })
        }
        else {
            console.log('error submit!', fields)
        }
    })
}

function close(formEl: FormInstance | undefined) {
    formEl && formEl.resetFields()
    emits('update:modelValue', false)
}

async function getGroup() {
    exploitGetGroup({ appCode: appItem.value.appCode }).then((res: any) => {
        groupIds.value = res
    })
}

async function init(isAdd = true) {
    await nextTick()
    const appId = appItem.value.id
    if ([3, 4].includes(appId))
        getGroup()

    if (isAdd) {
        form.value = { ...state }
        getMenuNo({ appId }).then((res: any) => {
            form.value.menuCode = res
        })
        title.value = '新增'
    }
    else {
        title.value = '编辑'
        const { groupList } = data.value
        const groupIds = groupList.length ? groupList.map((v: any) => v.id) : []
        form.value = { ...data.value, groupIds }
    }
}

defineExpose({
    init,
})
</script>

<template>
    <ElDialog v-model="modelValue"
              width="600"
              :close-on-click-modal="false"
              :title="title"
              @close="close"
    >
        <ElForm ref="formRef"
                label-position="top"
                :model="form"
                :rules="rules"
                label-width="auto"
                style="max-width: 600px"
        >
            <ElRow :gutter="20">
                <ElCol :span="12">
                    <ElFormItem label="应用名称"
                                prop="menuName"
                    >
                        <ElInput v-model="form.menuName" />
                    </ElFormItem>
                </ElCol>

                <ElCol :span="12">
                    <ElFormItem label="应用编码"
                                prop="menuCode"
                    >
                        <ElInput v-model="form.menuCode"
                                 disabled
                        />
                    </ElFormItem>
                </ElCol>
            </ElRow>

            <ElRow :gutter="20">
                <ElCol :span="12">
                    <ElFormItem label="应用链接"
                                prop="menuUrl"
                    >
                        <ElInput v-model="form.menuUrl" />
                    </ElFormItem>
                </ElCol>

                <ElCol :span="12">
                    <ElFormItem label="应用状态"
                                prop="status"
                    >
                        <ElSelect v-model="form.status"
                                  placeholder="请选择"
                                  size="large"
                        >
                            <ElOption v-for="item in status"
                                      :key="item.value"
                                      :label="item.label"
                                      :value="item.value"
                            />
                        </ElSelect>
                    </ElFormItem>
                </ElCol>
            </ElRow>

            <ElCol v-if="[3, 4].includes(appItem.id)"
                   :span="12"
            >
                <ElFormItem label="所属分组"
                            prop="groupIds"
                >
                    <ElSelect v-model="form.groupIds"
                              placeholder="请选择"
                              size="large"
                              collapse-tags
                              collapse-tags-tooltip
                              multiple
                    >
                        <ElOption v-for="item in groupIds"
                                  :key="item.id"
                                  :label="item.groupName"
                                  :value="item.id"
                        />
                    </ElSelect>
                </ElFormItem>
            </ElCol>

            <ElFormItem label="应用图标"
                        prop="menuPath"
            >
                <UpdatedOss v-model="form.menuPath" />
            </ElFormItem>

            <div style="text-align: center;">
                <ElButton type="primary"
                          @click="doSave(formRef)"
                >
                    确定
                </ElButton>

                <ElButton @click="close(formRef)">
                    取消
                </ElButton>
            </div>
        </ElForm>
    </ElDialog>
</template>
